<template>
  <div class="mall-layout">
    <!-- 左侧窄竖导航 -->
    <aside class="left-nav">
      <div class="logo">B3</div>
      <div class="nav-items">
        <button
          v-for="it in navItems"
          :key="it.key"
          class="nav-item"
          :class="{ active: activeKey === it.key }"
          @click="onNavClick(it)"
          :title="it.label"
        >
          <component :is="it.icon" class="icon" />
          <span class="label">{{ it.label }}</span>
        </button>
      </div>
    </aside>

    <!-- 主内容区 -->
    <main class="content">
      <RouterView />
    </main>

    <!-- 左侧抽屉：搜索 -->
    <transition name="slide-in">
      <section v-if="panelVisible && panelType==='search'" class="side-panel" @keyup.esc.window="closePanel">
        <div class="panel-header">
          <div class="title">导购搜索</div>
          <button class="close-btn" @click="closePanel">×</button>
        </div>
        <div class="panel-body">
          <div class="search-box">
            <el-input
              v-model="searchText"
              placeholder="输入SKU/名称按回车查找"
              clearable
              @keyup.enter.native="doSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-button type="primary" @click="doSearch">查询</el-button>
          </div>

          <div class="section">
            <div class="section-head">
              <div class="sec-title">搜索记录</div>
              <button class="link" @click="clearHistory" v-if="recentSearches.length">清空搜索记录</button>
            </div>
            <div class="tags" v-if="recentSearches.length">
              <span class="tag" v-for="kw in recentSearches" :key="kw" @click="applyKeyword(kw)">{{ kw }}</span>
            </div>
            <div v-else class="empty">暂无搜索记录</div>
          </div>
        </div>
      </section>
    </transition>

    <!-- 左侧抽屉：收藏 -->
    <transition name="slide-in">
      <section v-if="panelVisible && panelType==='favorites'" class="side-panel" @keyup.esc.window="closePanel">
        <div class="panel-header">
          <div class="title">导航收藏夹 <span class="muted">{{ favoriteCount }} 项收藏</span></div>
          <button class="close-btn" @click="closePanel">×</button>
        </div>
        <div class="panel-body">
          <div class="fav-groups">
            <div class="fav-group" v-for="group in favoriteGroups" :key="group.name">
              <div class="group-title">{{ group.name }}</div>
              <div class="group-items">
                <div class="fav-item" v-for="item in group.items" :key="item.path">
                  <span class="fav-name" @click="go(item.path)">{{ item.title }}</span>
                  <button class="star-btn" :class="{ on: isFav(item.path) }" @click="toggleFav(item.path)">
                    <el-icon><component :is="isFav(item.path) ? StarFilled : Star" /></el-icon>
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>
    </transition>

    <!-- 遮罩（覆盖内容区但不遮挡左侧导航） -->
    <div v-if="panelVisible" class="overlay" @click="closePanel"></div>
  </div>
</template>

<script setup>
import { computed, ref, watch } from 'vue'
import { useRoute, useRouter, RouterView } from 'vue-router'
import { ElInput, ElButton, ElIcon } from 'element-plus'
import { Search, Star, StarFilled, HomeFilled, Collection, Goods, ShoppingCartFull, Share, Box, Wallet, OfficeBuilding, User, DataAnalysis, Setting, Key } from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()

// 左侧导航配置（与截图一致的顺序）
const navItems = [
  { key: 'search', label: '搜索', icon: Search, type: 'panel' },
  { key: 'favorites', label: '收藏', icon: Star, type: 'panel' },
  { key: 'home', label: '首页', icon: HomeFilled, path: '/mall/dashboard' },
  { key: 'archives', label: '档案', icon: Collection, path: '/mall/archives' },
  { key: 'products', label: '商品', icon: Goods, path: '/mall/catalog' },
  { key: 'purchase', label: '采购', icon: ShoppingCartFull, path: '/mall/purchase' },
  { key: 'distribution', label: '分销', icon: Share, path: '/mall/transfers' },
  { key: 'inventory', label: '库存', icon: Box, path: '/mall/inventory' },
  { key: 'finance', label: '财务', icon: Wallet, path: '/mall/settlement' },
  { key: 'stores', label: '门店', icon: OfficeBuilding, path: '/mall/stores' },
  { key: 'members', label: '会员', icon: User, path: '/mall/members' },
  { key: 'reports', label: '报表', icon: DataAnalysis, path: '/mall/report-sales' },
  { key: 'system', label: '系统', icon: Setting, path: '/mall/settings' },
  { key: 'auth', label: '授权', icon: Key, path: '/mall/users' },
]

// 根据路由匹配当前激活项
const pathToKey = {
  '/mall/dashboard': 'home',
  '/mall/catalog': 'products',
  '/mall/colors': 'products',
  '/mall/sizes': 'products',
  '/mall/tags': 'products',
  '/mall/purchase': 'purchase',
  '/mall/transfers': 'distribution',
  '/mall/replenishments': 'distribution',
  '/mall/returns': 'distribution',
  '/mall/inventory': 'inventory',
  '/mall/stocktake': 'inventory',
  '/mall/loss': 'inventory',
  '/mall/settlement': 'finance',
  '/mall/stores': 'stores',
  '/mall/registers': 'stores',
  '/mall/members': 'members',
  '/mall/member-tiers': 'members',
  '/mall/points': 'members',
  '/mall/stored-value': 'members',
  '/mall/report-sales': 'reports',
  '/mall/report-matrix': 'reports',
  '/mall/report-season': 'reports',
  '/mall/report-aging': 'reports',
  '/mall/report-staff': 'reports',
  '/mall/retail-analytics': 'reports',
  '/mall/settings': 'system',
  '/mall/users': 'auth',
}

const activeKey = computed(() => pathToKey[route.path] || '')

// 抽屉面板
const panelVisible = ref(false)
const panelType = ref('search') // 'search' | 'favorites'

function onNavClick(it) {
  if (it.type === 'panel') {
    panelType.value = it.key
    panelVisible.value = true
    return
  }
  panelVisible.value = false
  if (it.path) router.push(it.path)
}

function closePanel() { panelVisible.value = false }
function go(path) { router.push(path); closePanel() }

// 搜索逻辑（简单记录关键词）
const searchText = ref('')
const recentSearches = ref(JSON.parse(localStorage.getItem('mall_recent_searches') || '[]'))

function saveHistory(arr) {
  localStorage.setItem('mall_recent_searches', JSON.stringify(arr.slice(0, 12)))
}

function doSearch() {
  const kw = (searchText.value || '').trim()
  if (!kw) return
  const arr = [kw, ...recentSearches.value.filter(v => v !== kw)]
  recentSearches.value = arr.slice(0, 12)
  saveHistory(recentSearches.value)
  // 这里可以跳转到某个搜索页；先进入库存页以便查看
  router.push('/mall/inventory')
}

function applyKeyword(kw) { searchText.value = kw; doSearch() }
function clearHistory() { recentSearches.value = []; saveHistory([]) }

// 收藏夹
const FAVORITE_KEY = 'mall_favorites'
const favoriteSet = ref(new Set(JSON.parse(localStorage.getItem(FAVORITE_KEY) || '[]')))
const favoriteGroups = [
  {
    name: '档案',
    items: [
      { title: '客户', path: '/mall/users' },
      { title: '会员', path: '/mall/members' },
      { title: '供应商', path: '/mall/suppliers' },
    ]
  },
  {
    name: '采购',
    items: [
      { title: '采购单', path: '/mall/purchase' },
      { title: '补货单', path: '/mall/replenishments' },
      { title: '退货单', path: '/mall/returns' },
    ]
  },
  {
    name: '门店',
    items: [
      { title: '门店资料', path: '/mall/stores' },
      { title: '收银点', path: '/mall/registers' },
      { title: '交接班', path: '/mall/shifts' },
    ]
  },
  {
    name: '报表',
    items: [
      { title: '销售分析', path: '/mall/report-sales' },
      { title: '款色尺码结构', path: '/mall/report-matrix' },
      { title: '库存老化', path: '/mall/report-aging' },
    ]
  },
]

const favoriteCount = computed(() => favoriteSet.value.size)
function isFav(path) { return favoriteSet.value.has(path) }
function persistFav() { localStorage.setItem(FAVORITE_KEY, JSON.stringify(Array.from(favoriteSet.value))) }
function toggleFav(path) {
  if (favoriteSet.value.has(path)) favoriteSet.value.delete(path)
  else favoriteSet.value.add(path)
  persistFav()
}
</script>

<style scoped>
.mall-layout {
  height: 100vh;
  width: 100vw;
  background: #f5f7fb;
}

/* 左侧窄竖导航 */
.left-nav {
  position: fixed;
  left: 0;
  top: 0;
  bottom: 0;
  width: 64px;
  background: #0f172a;
  color: #cbd5e1;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.logo {
  font-weight: 800;
  color: #fff;
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: center;
  letter-spacing: 1px;
}

.nav-items {
  display: flex;
  flex-direction: column;
  gap: 4px;
  padding: 6px 0;
  width: 100%;
}

.nav-item {
  width: 100%;
  height: 44px;
  background: transparent;
  border: none;
  color: #cbd5e1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 2px;
  cursor: pointer;
}

.nav-item .icon { font-size: 18px; }
.nav-item .label { font-size: 12px; line-height: 1; }
.nav-item:hover { background: rgba(255,255,255,.06); color: #fff; }
.nav-item.active { background: rgba(59,130,246,.18); color: #fff; }

/* 主体 */
.content {
  margin-left: 64px; /* 腾出导航宽度 */
  height: 100vh;
  overflow: auto;
}

/* 抽屉与遮罩 */
.side-panel {
  position: fixed;
  top: 0;
  left: 64px; /* 与导航对齐 */
  height: 100vh;
  width: 420px;
  max-width: 92vw;
  background: #fff;
  box-shadow: 2px 0 16px rgba(0,0,0,.08);
  display: flex;
  flex-direction: column;
  z-index: 1000;
}

.panel-header {
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 12px 0 16px;
  border-bottom: 1px solid #eef1f5;
}
.panel-header .title { font-weight: 600; }
.panel-header .muted { color: #6b7280; font-weight: 400; margin-left: 6px; font-size: 12px; }
.close-btn { border: none; background: transparent; font-size: 22px; cursor: pointer; }

.panel-body { padding: 12px; overflow: auto; }

.search-box { display: grid; grid-template-columns: 1fr auto; gap: 8px; }
.section { margin-top: 14px; }
.section-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 8px; }
.sec-title { font-weight: 600; color: #111827; }
.link { background: transparent; border: none; color: #2563eb; cursor: pointer; }
.tags { display: flex; flex-wrap: wrap; gap: 8px; }
.tag { background: #f3f4f6; padding: 6px 10px; border-radius: 999px; cursor: pointer; font-size: 12px; }
.empty { color: #9ca3af; font-size: 13px; }

.fav-groups { display: grid; grid-template-columns: 1fr 1fr; gap: 10px 16px; }
.group-title { color: #6b7280; font-weight: 600; margin-bottom: 6px; }
.fav-item { display: flex; align-items: center; justify-content: space-between; background: #f8fafc; border: 1px solid #eef1f5; border-radius: 8px; padding: 8px 10px; gap: 8px; }
.fav-name { cursor: pointer; }
.fav-name:hover { color: #2563eb; }
.star-btn { background: transparent; border: none; cursor: pointer; color: #9ca3af; }
.star-btn.on { color: #f59e0b; }

.overlay {
  position: fixed;
  left: 64px; /* 不遮挡左侧导航 */
  right: 0;
  top: 0;
  bottom: 0;
  background: rgba(0,0,0,.02);
  z-index: 999;
}

/* 动画 */
.slide-in-enter-active, .slide-in-leave-active { transition: transform .18s ease; }
.slide-in-enter-from, .slide-in-leave-to { transform: translateX(-12px); }
</style>


